package com.glodon.paas.document.web.security.spring.login;

import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.account.sdk.sso.web.AbstractCasSingleSignOnFilter;
import com.glodon.paas.consts.StringConst;
import org.jasig.cas.client.validation.Assertion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Don Li
 */
public class CasSingleSignOnFilterImpl extends AbstractCasSingleSignOnFilter {

    public static final Logger LOGGER = LoggerFactory.getLogger(CasSingleSignOnFilterImpl.class);

    @Override
    protected void handleSuccess(HttpServletRequest request, HttpServletResponse response) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            LOGGER.debug("authentication succeded");
            final Assertion assertion = (Assertion) request.getSession(false).getAttribute(AbstractCasSingleSignOnFilter.CAS_ASSERTION);
            final String ticket = (String) request.getSession(false).getAttribute(AbstractCasSingleSignOnFilter.CAS_SERVICE_TICKET);
            final User userInfo = (User) request.getSession(false).getAttribute(StringConst.USER_INFO);
            final CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, ticket);
            token.setDetails(userInfo);
            token.setAuthenticated(true);
            SecurityContextHolder.getContext().setAuthentication(token);
        }
    }
}
